import 'package:elevator/mqtt/mqtt_manager.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:typed_data/typed_data.dart';


import '../../model/user.dart';
import '../../mqtt/constant.dart';
import '../../mqtt/mqtt_call_back.dart';

class TestingLogic extends GetxController {


  var name = ''.obs;

  late User user;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    User user = Get.arguments;
    debugPrint("user:" + user.toString());
    setUser(user);
    loadInfo();
  }

  void setUser(User u) {
    user = u;
  }

  void loadInfo(){
    initState();
    startConnectMqtt();
  }

  late final AppLifecycleListener _listener;
  late AppLifecycleState? _state;
  void initState() {
    _state = SchedulerBinding.instance.lifecycleState;
    _listener = AppLifecycleListener(
      onShow: () => _handleTransition('show'),
      onResume: () => _handleTransition('resume'),
      onHide: () => _handleTransition('hide'),
      onInactive: () => _handleTransition('inactive'),
      onPause: () => _handleTransition('pause'),
      onDetach: () => _handleTransition('detach'),
      onRestart: () => _handleTransition('restart'),
    );
  }
  void _handleTransition(String state) {
    if(identical("show",state)){
      updateMsg("界面显示-------------");
    }else if(identical("hide",state)){
      updateMsg("界面隐藏-------------");
    }
  }

  late MQTTManager mqttManager;
  void startConnectMqtt(){
    if(null!=user && null!=user.psBuilds && user.psBuilds != ""){
      List<String> builds = [];
      if(user.psBuilds!.contains("/")){
        builds.addAll(user.psBuilds!.split("/"));
      }else{
        builds.add(user.psBuilds!);
      }
      mqttManager = MQTTManager();
      mqttManager.clentId = user.psName!;
      mqttManager.callBack = MqttCallBack(onConnected, onDisconnected, onSubscribed
          , onSubscribeFail, onUnsubscribed, onMessaged,pong);
      mqttManager.connect();
    }
  }


  // 连接成功
  void onConnected() {
    updateMsg("mqtt onConnected");
    MQTTManager mqttManager = MQTTManager();
    if(null!=user && null!=user.psBuilds && user.psBuilds != ""){
      List<String>? builds = user.psBuilds?.split("/");
      for(String buildId in builds!){
        mqttManager.subscribe(Constant.TOPIC_QUERY_SVP + buildId, MqttQos.atLeastOnce);
        mqttManager.subscribe(Constant.TOPIC_QUERY_TPC + buildId, MqttQos.atLeastOnce);
      }
    }
  }

  void onMessaged(String topic,Uint8Buffer byteBuffer){
    if(null!=topic && topic.isNotEmpty){
      if(topic.startsWith(Constant.TOPIC_QUERY_SVP)){
        parseSvp(topic,byteBuffer);
      }else if(topic.startsWith(Constant.TOPIC_QUERY_TPC)){
        parseTpc(topic,byteBuffer);
      }
    }
  }

  void parseSvp(String topic,Uint8Buffer byteBuffer){
    updateMsg("mqtt parseTpc-----");
  }

  void parseTpc(String topic,Uint8Buffer byteBuffer){
    updateMsg("mqtt parseTpc----");
  }

  // 连接断开
  void onDisconnected() {
    updateMsg("mqtt onDisconnected");
  }

  // 订阅主题成功
  void onSubscribed(String topic) {
    updateMsg("mqtt onSubscribed:$topic");
  }

  // 订阅主题失败
  void onSubscribeFail(String topic) {
    updateMsg("mqtt onSubscribeFail 订阅主题失败");
  }

  // 成功取消订阅
  void onUnsubscribed(String? topic) {
    updateMsg("mqtt onUnsubscribed 取消订阅");
  }

  // 收到 PING 响应
  void pong() {
    updateMsg("mqtt pong");
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    updateMsg("mqtt onClose");
  }

  void changeName() {
    name.value = '名称变动了';
  }

  void updateMsg(String msg) {
    if(name.value.length>4000){
      name.value = name.value.substring(name.value.length-4000,name.value.length);
    }
    DateTime dateTime = DateTime.now();
    name.value = "${name.value}\n$dateTime$msg";
  }

  void test(){
    MQTTManager().connect();
  }


}
